<?php

namespace app\admin\controller;

use app\admin\model\Nav;
use think\Controller;
use think\Request;

class NavController extends BaseController
{
    /**
     * 菜单列表
     * @return \think\response\View
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $navs = Nav::all();
        $parents = Nav::where('pid', 0)->select();
        return view('index', compact('navs', 'parents'));
    }

    /**
     * 添加
     * @param Request $request
     * @return \think\response\View|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add(Request $request)
    {
        if ($request->isPost()) {
            $data = $request->post();
            $validate = $this->validate($data, [
                'name|菜单名称' => 'require|unique:nav',
            ]);
            if ($validate !== true) {
                //验证没有通过
                return $this->error($validate);
            }
            $data['create_at'] = time();
            $data['update_at'] = time();
            $res = Nav::create($data);
            if ($res) {
                return $this->success('添加成功', 'index');
            } else {
                return $this->error('添加失败', 'add');
            }
        }
        $navs = Nav::where('pid', 0)->select();
        return view('add', compact('navs'));
    }

    /**
     * 修改
     * @param Request $request
     * @param $id
     * @return \think\response\View|void
     * @throws \think\exception\DbException
     */
    public function edit(Request $request, $id)
    {
        $nav = Nav::get($id);
        if ($request->isPost()) {
            $data = $request->post();
            $validate = $this->validate($data, [
                'name|菜单名称' => 'require',
            ]);
            if ($validate !== true) {
                //验证没有通过
                return $this->error($validate);
            }
            $data['update_at'] = time();
            $res = $nav->save($data);
            if ($res) {
                return $this->success('修改成功', 'index');
            } else {
                return $this->error('修改失败', 'edit');
            }
        }
        $navs = Nav::where('pid', 0)->select();
        return view('edit', compact('navs', 'nav'));
    }

    /**
     * 删除
     * @param $id
     * @throws \think\exception\DbException
     */
    public function del($id)
    {
        $nav = Nav::get($id);
        $res = $nav->delete();
        if ($res) {
            return $this->success('删除成功', 'index');
        } else {
            return $this->error('删除失败', 'index');
        }
    }
}
